package com.IntelligentCommunity.deploy.service.impl;

import com.IntelligentCommunity.algorithm.api.AlgorithmRemote;
import com.IntelligentCommunity.algorithm.domain.request.FaceAddRequest;
import com.IntelligentCommunity.common.core.utils.DateUtils;
import com.IntelligentCommunity.common.core.utils.StringUtils;
import com.IntelligentCommunity.common.core.utils.uuid.UUID;
import com.IntelligentCommunity.common.security.utils.SecurityUtils;
import com.IntelligentCommunity.deploy.cache.TaskFaceCache;
import com.IntelligentCommunity.deploy.domain.DeployTaskFace;
import com.IntelligentCommunity.deploy.domain.vo.DeployTaskFaceVO;
import com.IntelligentCommunity.deploy.mapper.DeployTaskFaceMapper;
import com.IntelligentCommunity.deploy.run.CacheJob;
import com.IntelligentCommunity.deploy.service.IDeployTaskFaceService;
import com.IntelligentCommunity.file.api.RemoteFileService;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抓拍任务Service业务层处理
 *
 * @author kwzjx
 * @date 2024-07-23
 */
@Service
public class DeployTaskFaceServiceImpl extends ServiceImpl<DeployTaskFaceMapper, DeployTaskFace> implements IDeployTaskFaceService
{
    @Autowired
    private AlgorithmRemote algorithmRemote;

    @Autowired
    private DeployTaskFaceMapper deployTaskFaceMapper;


    @Autowired
    private RemoteFileService remoteFileService;
    /**
     * 查询抓拍任务
     *
     * @param id 抓拍任务主键
     * @return 抓拍任务
     */
    @Override
    public DeployTaskFace selectDeployTaskFaceById(Long id)
    {
        return deployTaskFaceMapper.selectDeployTaskFaceById(id);
    }

    /**
     * 查询抓拍任务列表
     *
     * @param deployTaskFace 抓拍任务
     * @return 抓拍任务
     */
    @Override
    public List<DeployTaskFace> selectDeployTaskFaceList(DeployTaskFace deployTaskFace)
    {
        return deployTaskFaceMapper.selectDeployTaskFaceList(deployTaskFace);
    }

    /**
     * 新增抓拍任务
     *
     * @param deployTaskFace 抓拍任务
     * @return 结果
     */
    @Override
    public int insertDeployTaskFace(DeployTaskFace deployTaskFace)
    {
        deployTaskFace.setCreateTime(DateUtils.getNowDate());
        return deployTaskFaceMapper.insertDeployTaskFace(deployTaskFace);
    }

    /**
     * 修改抓拍任务
     *
     * @param deployTaskFace 抓拍任务
     * @return 结果
     */
    @Override
    public int updateDeployTaskFace(DeployTaskFace deployTaskFace)
    {
        // 删除人脸
        removeFace(deployTaskFace.getId());

        // 添加人脸
        String subject ="face,"+deployTaskFace.getId();
        FaceAddRequest faceAddRequest = new FaceAddRequest();
        faceAddRequest.setFlag(1);
        faceAddRequest.setImg(deployTaskFace.getTaskImages());
        faceAddRequest.setSubject(subject);
        algorithmRemote.faceInsert(faceAddRequest);
        // 更新任务
        return deployTaskFaceMapper.updateDeployTaskFace(deployTaskFace);
    }

    /**
     * 批量删除抓拍任务
     *
     * @param ids 需要删除的抓拍任务主键
     * @return 结果
     */
    @Override
    public int deleteDeployTaskFaceByIds(Long[] ids)
    {
        for (Long id : ids) {
            removeFace(id);
        }
        return deployTaskFaceMapper.deleteDeployTaskFaceByIds(ids);
    }

    /**
     * 删除抓拍任务信息
     *
     * @param id 抓拍任务主键
     * @return 结果
     */
    @Override
    public int deleteDeployTaskFaceById(Long id)
    {
        removeFace(id);
        return deployTaskFaceMapper.deleteDeployTaskFaceById(id);
    }

    @Transactional
    @Override
    public void deployTaskFaceAdd(DeployTaskFace deployTaskFace) {
        Double similarity = deployTaskFace.getSimilarity();
        deployTaskFace.setSimilarity(similarity);
        deployTaskFace.setUserId(SecurityUtils.getUserId());
        // 添加任务
        save(deployTaskFace);

        FaceAddRequest faceAddRequest = new FaceAddRequest();
        faceAddRequest.setImg(deployTaskFace.getTaskImages());
        faceAddRequest.setSubject("face,"+deployTaskFace.getId());
        faceAddRequest.setFlag(1);

        // 调用算法服务添加人脸
        algorithmRemote.faceInsert(faceAddRequest);
    }

    @Override
    public List<DeployTaskFaceVO> selectDeployTaskFaceVOList(DeployTaskFace deployTaskFace, Integer flag, String populationName, String idCardNumber) {

        if (flag != null && flag == -1){
            List<Long> ids = deployTaskFaceMapper.getPopulationTaskId();
            return deployTaskFaceMapper.selectDeployTaskFaceVOList(deployTaskFace, ids, populationName, idCardNumber);
        }

        List<DeployTaskFaceVO> deployTaskFaceVOS = deployTaskFaceMapper.selectDeployTaskFaceVOList(deployTaskFace, null, populationName, idCardNumber);
        return deployTaskFaceVOS;
    }

    @Transactional
    @Override
    public void pauseOrStart(String subject, Long id, Integer status) {

        List<Long> ids = new ArrayList<>();

        // id为-1代表批量处理数据
        if (id == -1){

            if (status == 2){
                // 一键暂停
                ids = batchRemoveFace();
            }else {
                // 一键开始
                ids = batchInsert();
            }

        }else {

            if (status == 1){
                // 添加人脸库
                ids = singleInsert(subject, id, 1);
            }else {
                // 删除人脸库
                ids.add(id);
                removeFace(id);
            }

        }

        if(ids.isEmpty()){
            throw new RuntimeException("别瞎点,已经没有这个状态的任务了,抓紧滚蛋");
        }

        // 修改状态
        deployTaskFaceMapper.pauseOrStart(ids, status);
       run();

    }
    public void run() {
        List<DeployTaskFaceVO> deployTaskFaces = selectDeployTaskFaceVOList(null, null, null, null);
        TaskFaceCache instance = TaskFaceCache.getInstance();
        if (instance.size() > 0) {
            instance.getTaskFaceCacheMap().clear();
        }
        for (DeployTaskFaceVO deployTaskFace : deployTaskFaces) {
            instance.put("face,"+deployTaskFace.getId(), deployTaskFace);
        }
    }

    private List<Long> batchRemoveFace() {

        List<String> subjects = new ArrayList<>();

        List<Long> ids = deployTaskFaceMapper.getAllStartTaskId();

        for (Long id : ids) {
            subjects.add("face," + id);
        }

        algorithmRemote.delBySubjects(subjects);

        return ids;

    }

    public List<Long> singleInsert(String subject, Long id, Integer flag) {

        List<Long> ids = new ArrayList<>();

        DeployTaskFace deployTaskFace = selectDeployTaskFaceById(id);
        FaceAddRequest faceAddRequest = new FaceAddRequest();
        faceAddRequest.setFlag(flag);
        faceAddRequest.setImg(deployTaskFace.getTaskImages());
        faceAddRequest.setSubject(subject);
        algorithmRemote.faceInsert(faceAddRequest);

        ids.add(id);

        return ids;
    }

    public List<Long> batchInsert() {

        List<Long> ids = new ArrayList<>();

        List<DeployTaskFace> deployTaskFaceList = deployTaskFaceMapper.getAllNotStartTask();
        List<FaceAddRequest> faceAddRequestList = new ArrayList<>();
        for (DeployTaskFace deployTaskFace : deployTaskFaceList) {
            FaceAddRequest faceAddRequest = new FaceAddRequest();
            faceAddRequest.setFlag(1);
            faceAddRequest.setImg(deployTaskFace.getTaskImages());
            faceAddRequest.setSubject("face,"+deployTaskFace.getId());
            faceAddRequestList.add(faceAddRequest);

            ids.add(deployTaskFace.getId());
        }
        algorithmRemote.faceInsertBath(faceAddRequestList);
        return ids;
    }


    @Override
    public List<String> selectTaskImagesById(Long id) {
        String imagesStr = deployTaskFaceMapper.selectTaskImagesById(id);
        String[] split = imagesStr.split(",");
        return Arrays.asList(split);
    }

    @Override
    public DeployTaskFaceVO selectDeployTaskDetailById(Long id) {
        DeployTaskFaceVO deployTaskFaceVO = deployTaskFaceMapper.selectDeployTaskDetailById(id);
        DeployTaskFaceVO info = deployTaskFaceMapper.selectdeployTaskPopulationInfoById(id);
        if (info != null) {
            deployTaskFaceVO.setPopulationName(info.getPopulationName());
            deployTaskFaceVO.setIdCardNumber(info.getIdCardNumber());
        }
        return deployTaskFaceVO;
    }

    @Transactional
    @Override
    public void deployPopulationAdd(DeployTaskFace deployTaskFace, Long id) {
        deployTaskFace.setUserId(SecurityUtils.getUserId());
        deployTaskFaceMapper.insertDeployTaskFace(deployTaskFace);
        deployTaskFaceMapper.insertRePopulationTask(deployTaskFace.getId(),id);
        singleInsert("person_id,"+deployTaskFace.getId(),deployTaskFace.getId(),0);
    }

    @Override
    public void startTimeUpButNotStartTask() {
        deployTaskFaceMapper.startTimeUpButNotStartTask();
    }

    private void removeFace(Long id){
        algorithmRemote.delBySubject("face,"+id);
    }


}
